<template>
    <div class="px-8">
        <com-filterTable
            :ref="pageConfig.key"
            class=""
            :services="pageConfig.serviceHandle"
            :filter-form-config="pageConfig.formConfig"
            :filterInline="false"
            :params="{}"
            :filterCol="4"
            filterLabelWidth="90px"
            :table-border="true"
            :showFormFilter="true"
            :showRequestNum="false"
            :top-operation="pageConfig.topOperation"
            :table-column="pageConfig.columnConfig"
            :queryDataHandle="queryDataHandle"
            :dataFormatHandle="dataFormatHandle"
            :autoLoad="true"
        />
        <com-formDialog
            ref="dialog"
            v-bind="dialogData"
            @changeOut="changeOut"
            @cancel="dialogCancelHandle"
            @submit="submitHandle"
        />
    </div>
</template>

<script>
import { selectVisitList, createVisit, updateVisit, deleteVisit, selectPatientVitalSignsByPatientId } from "@/service/api.js";
import moment from "moment";
import { formFieldDoctor } from "@/utils/formFieldDoctor";
import {VISIT_TYPE, VISIT_STATUS} from "@/utils/enum.js"
import Life from "./components/life.vue"
export default {
    name: "visitManage",
    data() {
        return {
            activeName: "filterTable",
            comDialogData: {},
            oldFormData: null,
            pageConfig: {
                key: "filterTable",
                serviceHandle: (data) => {
                    return selectVisitList(data);
                },
                params: {},
                formConfig: [
                    { key: "id", label: "就诊ID" },
                    // { key: "patientId", label: "患者ID" },
                    formFieldDoctor.patient.call(this, "患者", "patientId", {
                    }),
                    // { key: "visitNo", label: "就诊号" },
                ],
                columnConfig: [
                    // { type: "select" },
                    { value: "visitNo", label: "就诊号" },
                    { value: "patientId", label: "患者ID" },
                    { value: "departmentId", label: "科室ID" },
                    { value: "doctorId", label: "医生ID" },
                    {
                        value: "visitType",
                        label: "就诊类型",
                        formatter: (row) => {
                            return row.visitType === 1 ? "门诊" : "住院";
                        },
                    },
                    { value: "visitTime", label: "就诊时间" },
                    { value: "chiefComplaint", label: "主诉" },
                    { value: "presentIllness", label: "现病史" },
                    {
                        value: "action",
                        type: "render",
                        width: 200,
                        label: "操作",
                        render: (h, { data: { row } }) => {
                            const editBtn = (
                                <el-button type="text" on-click={() => this.addOrEditHandle(row)}>修改</el-button>
                            );
                            const delBtn = (
                                <el-button type="text" on-click={() => this.deleteList([row])}>删除</el-button>
                            );
                            const queryBtn = (
                                <el-button type="text" on-click={() => this.queryPatientVitalSigns(row)}>详情</el-button>
                            );

                            return [editBtn, queryBtn];
                        },
                    },
                ],
                topOperation: {
                    left: [
                        {
                            name: "新增",
                            key: "add",
                            type: "primary",
                            requireArguments: ["batchSelected", "filterForm"],
                            handle: (batchSelected) => {
                                this.addOrEditHandle();
                            },
                        },
                    ],
                },
            },
        };
    },
    computed: {
        dialogData() {
            let { comDialogData } = this;
            return {
                configs:
                    this[comDialogData.configName] || comDialogData.configs,
                ...comDialogData,
            };
        },
    },
    methods: {
        changeOut({ key, formData } = {}) {
            this.oldFormData = { ...formData };
        },
        dataFormatHandle(data) {
            return {
                list: data.rows,
                total: data.total,
            };
        },
        queryDataHandle(params) {
            return params;
        },
        loadList() {
            let ref = this.$refs[this.activeName];
            if (Array.isArray(ref)) {
                ref = ref[0];
            }
            ref.filterFormQueryHandle();
        },
        dialogCancelHandle() {
            this.$refs.dialog.close();
        },
        async submitHandle(data) {
            let handle = this.dialogData.submitHandle;
            handle = typeof handle !== "function" ? this[handle] : handle;
            if (handle) {
                let loading = await this.$store.dispatch("global/loading");
                handle(data)
                    .then((res) => {
                        loading.close();
                        this.$refs.dialog.close();
                        this.loadList();
                    })
                    .catch((e) => {
                        console.log(e);
                        loading.close();
                    });
            }
        },
        addOrEditHandle(row, isDetail) {
            this.comDialogData = {
                submitHandle: (data) => {
                    let handle = createVisit;
                    let params = { ...data };
                    if (row) {
                        handle = updateVisit;
                        params.id = row.id;
                    }
                    return handle(params);
                },
                initFormData: row,
                configs: [
                    // { key: "patientId", label: "患者ID", required: true },
                    formFieldDoctor.patient.call(this, "患者", "patientId", {
                        required: true,
                        disabled: !!row,
                    }, {
                        disabled: !!row,
                        formChangeHandle: (vm, data) => {
                            let patient = this.patientMap?.[data];
                            if(patient) {
                                vm.setFormData({
                                    visitNo: patient.medicalRecordNo, // 就诊号
                                })
                            }
                        },
                        onDataMapHandle: (data) => {
                            this.patientMap = data;

                        }
                    }),
                    { key: "visitNo", label: "就诊号", required: true,disabled: !!row, },
                    {
                        key: "visitType",
                        label: "就诊类型",
                        required: true,
                        type: "select",
                        disabled: isDetail,
                        options: Object.values(VISIT_TYPE),
                    },
                    formFieldDoctor.depart.call(this, '就诊科室', 'departmentId', {
                        required: true
                        
                    }, {disabled: isDetail,}),
                    formFieldDoctor.user.call(this, '就诊医生', 'doctorId', {
                        required: true
                    }, {disabled: isDetail,}),
                    { key: "visitTime", label: "就诊时间", required: true, type: "datetime" ,disabled: isDetail,},
                    { key: "chiefComplaint", label: "主诉", required: true, fullLine: true ,disabled: isDetail},
                    { key: "presentIllness", label: "现病史", required: true, fullLine: true ,disabled: isDetail},
                    {
                        key: "status",
                        label: "状态",
                        required: true,
                        disabled: isDetail,
                        type: "select",
                        options: Object.values(VISIT_STATUS),
                    },
                    { key: "admissionTime", label: "入院时间", type: "datetime",disabled: isDetail },
                    { key: "dischargeTime", label: "出院时间", type: "datetime" ,disabled: isDetail},
                    ...(isDetail ? [{
                        key: 'life',
                        label: '',
                        noLabel: true,
                        fullLine: true,
                        type: 'render',
                        render: (h) => {
                            return <Life patientId={row.patientId}></Life>
                        }
                    }] : [])

                ],
                activeRow: row,
                title: row ? "修改" : "新增",
                width: "750px",
                height: isDetail ? "600px" :"400px",
                labelPosition: "left",
                labelWidth: "110px",
                col: 2,
                ...(isDetail ? {
                    slotRenders: {
                        footer: (h) => {
                            return <div></div>;
                        },
                    },
                } : {})

            };
            this.$refs.dialog.show();
        },
        queryPatientVitalSigns(row) {
            this.addOrEditHandle(row, true)
            // selectPatientVitalSignsByPatientId({ patientId: row.patientId })
            //     .then(res => {
            //         if (res.success) {
            //             this.$alert(`
            //                 <div>
            //                     <p>身高: ${res.data.height} cm</p>
            //                     <p>体重: ${res.data.weight} kg</p>
            //                     <p>体温: ${res.data.temperature} ℃</p>
            //                     <p>脉搏: ${res.data.pulse} 次/分</p>
            //                     <p>收缩压: ${res.data.systolicPressure} mmHg</p>
            //                     <p>舒张压: ${res.data.diastolicPressure} mmHg</p>
            //                 </div>
            //             `, '患者体征信息', {
            //                 dangerouslyUseHTMLString: true
            //             });
            //         }
            //     });
        },
        deleteList(list) {
            let params = {
                id: list.map(item => item.id).join(',')
            };
            this.$confirm("确定要删除吗？").then(() => {
                this.comDialogData = {
                    submitHandle: () => {
                        return deleteVisit(params);
                    }
                };
                this.submitHandle();
            });
        },
    },
};
</script>